<template>
  <form @submit.prevent="handleAddTodo" class="flex gap-2 mb-6">
    <input 
      type="text" 
      v-model="newTodoText" 
      placeholder="输入新的任务..." 
      class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all"
      :class="{ 'border-red-500': isInvalid }"
      @input="clearError"
    >
    <button 
      type="submit" 
      class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg transition-all flex items-center gap-2"
    >
      <i class="fa fa-plus"></i>
      <span>添加</span>
    </button>
  </form>
</template>

<script setup>
import { ref } from 'vue';

// 定义组件发出的事件
const emit = defineEmits(['add-todo']);

// 响应式变量
const newTodoText = ref('');
const isInvalid = ref(false);

// 处理添加任务
const handleAddTodo = () => {
  const text = newTodoText.value.trim();
  
  if (!text) {
    isInvalid.value = true;
    return;
  }
  
  // 发出事件，将新任务传递给父组件
  emit('add-todo', text);
  
  // 清空输入框
  newTodoText.value = '';
};

// 清除错误状态
const clearError = () => {
  isInvalid.value = false;
};
</script>
